
/**日志记录方法*/

var fs = require('fs');
var path = require('path');
var morgan = require('morgan');
var time = new Date();
var addZero = function (num) {
    return num > 9 ? num : '0' + num
}
var todayDate = [time.getFullYear(), addZero(time.getMonth() + 1), addZero(time.getDate())].join('');
var nowTime = [time.getFullYear(), addZero(time.getMonth() + 1), addZero(time.getDate())].join('-') + " " + [time.getHours(), time.getMinutes(), time.getSeconds()].join(":");

var logStream = fs.createWriteStream(path.resolve('/', `./${todayDate}.log`), {
    flags: 'a'
})

morgan.token('localDate', function getDate(req) {
    let date = new Date();
    return date.toLocaleString()
})


function setLog() {
    //morgan路由网络错误日志写入(除过200状态码)
    return (
        morgan(
            ":localDate :remote-addr :url :status :user-agent", {
            stream: logStream,
            skip: function (req, res) {
                return res.statusCode == 200
            }
        }
        )
    );
}

function setErrorLog(type, msg_en, msg_ch, res_json) {
    //主动抛出异常日志写入
    fs.appendFileSync(path.resolve('/', `./${todayDate}.log`), `[${nowTime}] ${type} ${msg_en} ${msg_ch} ${res_json} \n`);
}

module.exports = {
    setLog,
    setErrorLog
};